using System;
using System.Globalization;
using System.Xml;

namespace FreeFlow.Client
{
	/// <summary>
	/// A number field.
	/// </summary>
	[Serializable]
	public class NumberField : Field
	{
    internal NumberField(Form form, XmlElement fieldNode)
      : base(form, fieldNode)
    {
      if (fieldNode != null)
      {
        decimalPlaces = int.Parse(fieldNode.GetAttribute("Decimals"));
        if (fieldNode.Attributes["Min"] != null)
          minimum = double.Parse(fieldNode.GetAttribute("Min"));
        if (fieldNode.Attributes["Max"] != null)
          maximum = double.Parse(fieldNode.GetAttribute("Max"));
      }
    }

    #region properties
    private int decimalPlaces;
    /// <summary>
    /// Gets the number of decimal places to be displayed for the number field.
    /// </summary>
    public int DecimalPlaces
    {
      get
      {
        return decimalPlaces;
      }
    }

    private double minimum = double.NegativeInfinity;
    /// <summary>
    /// Gets the minimum allowed value for this field.
    /// </summary>
    public double Minimum
    {
      get
      {
        return minimum;
      }
    }

    private double maximum = double.PositiveInfinity;
    /// <summary>
    /// Gets the maximum allowed value for this field.
    /// </summary>
    public double Maximum
    {
      get
      {
        return maximum;
      }
    }

    #endregion

    /// <summary>
    /// Gets the validation message.
    /// </summary>
    /// <returns>Returns null if the field has no validation errors, an error message otherwise.</returns>
    public override string GetValidationMessage()
    {
      if (Usage == FieldUsage.Required)
        if (string.IsNullOrEmpty(Value) || (Value == "0"))
          return FieldMustBeCompleted;

      // can this be recognised as a number?
      double parsedValue;
      if (double.TryParse(Value, NumberStyles.Any, CultureInfo.InvariantCulture, out parsedValue))
      {
        // min
        if (parsedValue < minimum)
          return "The value is less than the minimum allowed value of " + minimum.ToString();
      
        // max
        if (parsedValue > maximum)
          return "The value is more than the maximum allowed value of " + maximum.ToString();
      }
      else if (!string.IsNullOrEmpty(Value))
        return "The field does not contain a valid number";

      return null;
    }
	}
}
